#include<iostream>
#include<ctime>
#include<unistd.h>
#include"RingQueue.hpp"
#include"task.hpp"

using namespace std;
struct ThreadData
{
    RingQueue<Task>* rq;
    string threadname;
};

void* Consumer(void* args)
{
    ThreadData* data=static_cast<ThreadData*>(args);
    RingQueue<Task>* rq=data->rq;
    string name=data->threadname;
    while(true)
    {
        //消费任务
        Task t;
        rq->Pop(&t);

        //处理任务
        t.run();
        printf("消费者得到一个任务：%s,who:%s,结果：%s\n",t.GetTask().c_str(),name.c_str(),t.GetResult().c_str());
        //用printf输出比较好，不会错乱，cout打印有时会错乱
        // cout<<"消费者得到一个任务："<<t.GetTask()<<",who: "<<name<<"，结果为："<<t.GetResult()<<endl;
        // sleep(1);

    }
    return nullptr;
}
void* Producter(void* args)
{
    ThreadData* data=static_cast<ThreadData*>(args);
    RingQueue<Task>* rq=data->rq;
    string name=data->threadname;
    while(true)
    {
        //获取数据
        int data1=rand()%10+1;
        int data2=rand()%5;
        char op=opers[rand()%opers.size()];
        Task t(data1,data2,op);

        //生产任务
        rq->Push(t);
        printf("生产者生产一个任务：%s,who:%s\n",t.GetTask().c_str(),name.c_str());
        //用printf输出比较好，不会错乱，cout打印有时会错乱
        // cout<<"生产者生产一个任务："<<t.GetTask()<<",who: "<<name<<endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr));
    RingQueue<Task>* rq=new RingQueue<Task>(10);

    pthread_t c[5], p[3];

    for (int i = 0; i < 3; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Productor-" + std::to_string(i);

        pthread_create(p + i, nullptr, Producter, td);
    }
    for (int i = 0; i < 5; i++)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Consumer-" + std::to_string(i);

        pthread_create(c + i, nullptr, Consumer, td);
    }

    for (int i = 0; i < 3; i++)
    {
        pthread_join(p[i], nullptr);
    }
    for (int i = 0; i < 5; i++)
    {
        pthread_join(c[i], nullptr);
    }

    return 0;
}